﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Controllers
{
    /// <summary>
    /// 自定义Json视图
    /// </summary>
    public class CustomJsonResult : ActionResult
    {
        public object Data { get; set; }

        public string DateTimeFormat { get; set; } = "yyyy-MM-dd HH:mm:ss";

        //public PropertyNameResolver Resolver { get; set; } = PropertyNameResolver.CamelCase;


        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException(nameof(context));
            var response = context.HttpContext.Response;
            response.ContentType = "application/json";
            if (Data == null) return;
            string json;
            var settings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            };

            if (string.IsNullOrEmpty(DateTimeFormat))
            {
                json = JsonConvert.SerializeObject(Data, settings);
            }
            else
            {
                settings.Converters = new List<JsonConverter>
                {
                    new IsoDateTimeConverter {DateTimeFormat = DateTimeFormat}
                };
                json = JsonConvert.SerializeObject(Data, Formatting.Indented, settings);
            }

            var data = Encoding.UTF8.GetBytes(json);
            response.BinaryWrite(data);
        }
    }
}